package com.khh.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-07.
 */
@Controller
public class Download {

    @RequestMapping("/downloadspring")
    public ResponseEntity<byte[]> download(String fn, HttpServletRequest req) throws IOException {
        String fileName = fn;
        String downname = new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date())+fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String path = req.getServletContext().getRealPath("/upload/");
        InputStream is = new FileInputStream(path+"/"+fileName);
        byte[] buf = new byte[is.available()];
        is.read(buf);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + downname);
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(buf, headers, HttpStatus.OK);
        return entity;
    }

}
